package com.interactive.internal.ant;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;

import abbot.finder.AWTHierarchy;
import abbot.finder.Hierarchy;
import abbot.script.Launch;
import abbot.script.Script;

/**
 * Generates skeleton abbot scripts
 *
 * @author Ben Rady
 * @version 1.0
 */
public class ScriptCreator extends Task
{
  private static final Hierarchy DUMMY_HIERARCHY = new AWTHierarchy();
  private String path;
  private File file;

  public ScriptCreator() throws IOException
  {
    file = File.createTempFile("temp", "abbot");
  }

  public void setClasspathref(Reference classpath)
  {
    Path absolutePath = (Path)classpath.getReferencedObject(getProject());
    path = convertToRelativePath(absolutePath, getProject().getBaseDir().getAbsolutePath());
  }

  String convertToRelativePath(Path absolutePath, String basedir) throws BuildException
  {
    // Why does the list() method return an array?!?
    StringBuffer relativePath = new StringBuffer();
    String[] pathElements = absolutePath.list();
    int index = basedir.length() + 1;
    for(int i = 0; i < pathElements.length; i++)
    {
      String file = pathElements[i];
      if (pathElements[i].indexOf(basedir) != -1)
      {
        file = file.substring(index);
      }
      relativePath.append(file);
      relativePath.append(File.pathSeparator);
    }
    return relativePath.toString();
  }

  public void setScriptFile(File scriptFile)
  {
    file = scriptFile;
  }

  public void execute()
  {
    Script script = new Script(DUMMY_HIERARCHY);
    Launch launch = new Launch(script.getResolver(), "Launch", "bsh.Console", "main", new String[]{"[]"}, path.toString(), false);
    script.addStep(launch);
    script.setFile(file);
    try
    {
      script.save();
    }
    catch (IOException ex)
    {
      ex.printStackTrace();
      log("Error saving script file: " + file.getAbsolutePath(), Project.MSG_ERR);
    }
  }
}
